<template>
  <view
    class="page_root"
    data-page-name="新建产研交付日报（定制）"
    data-page-identification="w_8j7r3bmhuq"
  >
    <!-- UNI_APP_EXEGESIS_START NAVIGATION_TEMPLATE UNI_APP_EXEGESIS_END -->
    <!-- begin vid_1a58lh4qgl 自定义模板_zr0ranbda9 -->
    <u-navbar
      back-icon-color="#fff"
      title="新建产研交付日报"
      title-color="#fff"
      :border-bottom="false"
      title-width="350"
    >
    </u-navbar>
    
    <u-modal
      title="请确认"
      v-model="recordState.show"
      show-cancel-button
      @confirm="handleConfirmSubmit"
      :title-style="{ padding: 0, marginTop: '10px', marginBottom: '10px' }"
    >
      <view class="sub-tip">
        正在提交工时：{{ recordState.editHour }}工时 <br />
        今日已提交总工时(含本次提交)：{{ recordState.allHour + recordState.editHour }}工时
      </view>
    </u-modal>
    <u-mask :show="maskShow" @click="show = false">
      <view class="warp">
        <view class="rect">{{ maskTip }} </view>
      </view>
    </u-mask>
    <view class="card">
      <view class="custom-tabs">
        <view
          class="custom-tab"
          :class="{ active: recordState.current === 0 }"
          @click="tabChange(0)"
        >
          {{ recordState.subsectionList[0].name }}
          <view v-if="recordState.current === 0" class="custom-tab-underline"></view>
        </view>
        <view
          class="custom-tab"
          :class="{ active: recordState.current === 1 }"
          @click="tabChange(1)"
        >
          {{ recordState.subsectionList[1].name }}
          <view v-if="recordState.current === 1" class="custom-tab-underline"></view>
        </view>
      </view>
      <view class="notice-bar-content">
        <u-notice-bar
          border-radius="8"
          mode="horizontal"
          bg-color="rgba(51,102,255,0.10)"
          :list="recordState.topList"
          color="#3366FF"
          volume-icon="false"
        ></u-notice-bar>
      </view>
      <view class="scroll-content">
        <u-picker
          v-model="recordState.dateShow"
          mode="time"
          title="请选择工时对应时间"
          @confirm="onTimeConfirm"
          @cancel="onCancel"
        ></u-picker>
        <u-form-item
          required="true"
          label-position="top"
          label="请选择工时对应时间"
          prop="dailyDate"
          :rules="rules"
        >
          <u-input
            border="true"
            placeholder="请选择工时对应时间"
            type="select"
            v-model:modelValue="recordState.dailyDate"
            @click="recordState.dateShow = true"
          ></u-input>
        </u-form-item>

        <view class="project-daily" v-if="recordState.current === 1">
          <u-form :model="item" ref="projectDailyRef" :borderBottom="false">
            <view
              class="project-daily-item"
              :class="{ 'bottom-border': recordState.projectDailyData.length > 1 }"
              v-for="(item, index) in recordState.projectDailyData"
              :key="index"
            >
              <view class="daily-father-project">
                <view class="daily-title">项目{{ index + 1 }}</view>
              </view>

              <u-form-item label-position="top" label="项目名称或代号" :borderBottom="false">
                <u-input
                  border="true"
                  v-model:modelValue="item.projectName"
                  class="input-disabled"
                ></u-input>
              </u-form-item>
              <u-form-item label-position="top" label="工时">
                <u-input
                  type="number"
                  border="true"
                  class="work-hour-input"
                  placeholder="请输入工时"
                  v-model:modelValue="item.workingHours"
                  @blur="projectInputChange(index)"
                ></u-input>
                <view v-if="item.isValid === false" class="valid-span"
                  >请输入大于0小于等于8的数字(支持0.5的倍数)</view
                >
              </u-form-item>
            </view>
          </u-form>
        </view>

        <view class="task-daily" v-else>
          <u-form :model="item" ref="taskDailyRef" :rules="rules">
            <view
              class="task-daily-item"
              :class="{ 'bottom-border': recordState.taskDailyData.length > 1 }"
              v-for="(item, index) in recordState.taskDailyData"
              :key="index"
            >
              <view class="daily-father-task">
                <view class="daily-title">任务{{ index + 1 }}</view>
              </view>

              <u-form-item label-position="top" label="项目名称或代号">
                <u-input
                  border="true"
                  v-model:modelValue="item.projectName"
                  class="input-disabled"
                ></u-input>
              </u-form-item>
              <u-form-item label-position="top" label="里程碑项目阶段/用户故事">
                <u-input
                  border="true"
                  v-model:modelValue="item.milepostName"
                  class="input-disabled"
                ></u-input>
              </u-form-item>
              <u-form-item label-position="top" label="任务">
                <u-input
                  border="true"
                  v-model:modelValue="item.taskName"
                  class="input-disabled"
                ></u-input>
              </u-form-item>
              <u-form-item label-position="top" label="工时">
                <u-input
                  type="number"
                  border="true"
                  placeholder="请输入工时"
                  v-model:modelValue="item.workingHours"
                  @blur="taskInputChange(index)"
                ></u-input>
                <view v-if="item.isValid === false" class="valid-span"
                  >请输入大于0小于等于8的数字(支持0.5的倍数)</view
                >
              </u-form-item>
              <u-form-item
                label-position="top"
                label="是否有风险"
                :prop="[index, 'risk']"
                style="margin-top: 10px"
              >
                <u-radio-group v-model="item.risk" @change="radioGroupChange">
                  <u-radio
                    v-for="(item, index) in recordState.riskList"
                    :key="index"
                    :name="item.name"
                    :disabled="item.disabled"
                  >
                    {{ item.name }}
                  </u-radio>
                </u-radio-group>
              </u-form-item>
              <u-form-item
                label-position="top"
                label="风险描述"
                :prop="[index, 'riskDescription']"
                v-if="item.risk === '是'"
              >
                <u-input
                  border="true"
                  placeholder="请输入风险描述"
                  v-model:modelValue="item.riskDescription"
                ></u-input>
              </u-form-item>
              <u-form-item
                label-position="top"
                label="解决方案"
                :prop="[index, 'solution']"
                v-if="item.risk === '是'"
              >
                <u-input
                  border="true"
                  placeholder="请输入解决方案"
                  v-model:modelValue="item.solution"
                ></u-input>
              </u-form-item>
            </view>
          </u-form>
          <!-- 行动项任务 -->
          <u-form :model="item" ref="taskDailyRef" :rules="rules">
            <view
              class="task-daily-item"
              :class="{ 'bottom-border': recordState.actionDailyData.length > 1 }"
              v-for="(item, index) in recordState.actionDailyData"
              :key="index"
            >
              <view class="daily-father-project">
                <view class="daily-title">行动项任务{{ index + 1 }}</view>
              </view>

              <u-form-item label-position="top" label="项目名称或代号">
                <u-input
                  border="true"
                  v-model:modelValue="item.projectName"
                  class="input-disabled"
                ></u-input>
              </u-form-item>
              <u-form-item label-position="top" label="行动项任务">
                <u-input
                  border="true"
                  v-model:modelValue="item.taskName"
                  class="input-disabled"
                ></u-input>
              </u-form-item>
              <u-form-item label-position="top" label="工时">
                <u-input
                  type="digit"
                  border="true"
                  placeholder="请输入工时"
                  v-model:modelValue="item.workingHours"
                  @blur="taskInputChange(index)"
                ></u-input>
                <view v-if="item.isValid === false" class="valid-span"
                  >请输入大于0小于等于8的数字(支持0.5的倍数)</view
                >
              </u-form-item>
              <u-form-item
                label-position="top"
                label="是否有风险"
                :prop="[index, 'risk']"
                style="margin-top: 10px"
              >
                <u-radio-group v-model="item.risk" @change="radioActionGroupChange">
                  <u-radio
                    v-for="(item, index) in recordState.riskList"
                    :key="index"
                    :name="item.name"
                    :disabled="item.disabled"
                  >
                    {{ item.name }}
                  </u-radio>
                </u-radio-group>
              </u-form-item>
              <u-form-item
                label-position="top"
                label="风险描述"
                :prop="[index, 'riskDescription']"
                v-if="item.risk === '是'"
              >
                <u-input
                  border="true"
                  placeholder="请输入风险描述"
                  v-model:modelValue="item.riskDescription"
                ></u-input>
              </u-form-item>
              <u-form-item
                label-position="top"
                label="解决方案"
                :prop="[index, 'solution']"
                v-if="item.risk === '是'"
              >
                <u-input
                  border="true"
                  placeholder="请输入解决方案"
                  v-model:modelValue="item.solution"
                ></u-input>
              </u-form-item>
            </view>
          </u-form>
        </view>
        <!-- end -->
      </view>
    </view>
    <view class="bottom-btn">
      <u-button :custom-style="customStyle" @click="handlerCancel">取消</u-button>
      <u-button :custom-style="customStyle" @click="handlerSubmit(false)">保存</u-button>
      <u-button :custom-style="customStyleSubmit" @click="handlerSubmit(true)">保存并提交</u-button>
    </view>
    <!-- end vid_1a58lh4qgl 自定义模板_zr0ranbda9 -->
  </view>
</template>
<script setup>
  import {
    ref,
    reactive,
    toRaw,
    markRaw,
    watch,
    computed,
    onBeforeMount,
    onMounted,
    onBeforeUnmount,
    onUnmounted,
    onActivated,
    onDeactivated,
    getCurrentInstance,
  } from 'vue';
  import { useRoute } from 'vue-router';
  const route = useRoute();
  import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
  import {
    cloneDeep,
    localGet,
    traversalTreeStructure,
    set,
    checkCaseCondition,
    throttle,
    merge,
    debounce,
    getGridStyle,
    getCellRenderAble,
    formulaStrategy,
    getApplicationId,
    getComponentParamsValue,
    get as lodashGet,
  } from '@/utils/index';
  import {
    isEqual,
    isNullOrEmpty,
    isEmptyArr,
    isArray,
    isEmpty,
    isNullOrUnDef,
    isContained,
  } from '@/utils/is';
  import { CovertOptions, getChartsDataSourceConvert } from '@/utils/chart';
  import {
    propertyFormatByNumber,
    propertyFormatByPercentage,
    propertyFormatByDate,
    parseSubFromDataList,
  } from '@/utils/format';
  import { checkCommonCondition, getResultByCurrentCommonCondition } from '@/utils/formCondition';
  import { FormFormat } from '@/utils/formFormat';
  import { customAddWaterMarkFunc, generateWaterMarkText } from '@/utils/addWaterMark';
  import dayjs from 'dayjs';
  import hashSum from 'hash-sum';
    import { handleRedirect} from '@/utils/common';
  /*** UNI_APP_EXEGESIS ***
  import { handleRedirect, permission, parseJson } from '@/utils/common';
  import { onPullDownRefresh, onLoad, onReady, onShow, onHide, onPageScroll, onUnload } from '@dcloudio/uni-app';
  import { BroadcastMessage } from '@/utils/BroadcastMessage';
  import { sendToken } from "@/hooks/useIframeToken";
  *** UNI_APP_EXEGESIS ***/

  // ---------------------------- 属性定义 ----------------------------
  const sourceId = 'page3000000037';

  // 获取传入的流程ID和组件参数
  const props = defineProps({
    processInstanceId: {
      type: [String, Number, Boolean],
      default: undefined,
    },
    hideNav: {
      type: [Boolean],
      default: undefined,
    },
  });

  // 组件参数默认值
  const componentParamsDefaultProps = {};

  // 是否显示菜单按钮
  const isMenuIconShow = false;
  // NAVIGATION_MENU
  const handleShowNavigation = () => {};

  let isProcessState = ref(false);

  const setTimeOutList = [];

  const vid_1a58lh4qgl_props = reactive({
    code: '    <u-navbar\n      back-icon-color="#fff"\n      title="新建产研交付日报"\n      title-color="#fff"\n      :border-bottom="false"\n      title-width="350"\n    >\n    </u-navbar>\n    <u-modal\n      title="请确认"\n      v-model="recordState.show"\n      show-cancel-button\n      @confirm="handleConfirmSubmit"\n      :title-style="{ padding: 0, marginTop: \'10px\', marginBottom: \'10px\' }"\n    >\n      <view class="sub-tip">\n        正在提交工时：{{ recordState.editHour }}工时 <br />\n        今日已提交总工时(含本次提交)：{{ recordState.allHour + recordState.editHour }}工时\n      </view>\n    </u-modal>\n    <u-mask :show="maskShow" @click="show = false">\n      <view class="warp">\n        <view class="rect">{{ maskTip }} </view>\n      </view>\n    </u-mask>\n    <view class="card">\n      <view class="custom-tabs">\n        <view\n          class="custom-tab"\n          :class="{ active: recordState.current === 0 }"\n          @click="tabChange(0)"\n        >\n          {{ recordState.subsectionList[0].name }}\n          <view v-if="recordState.current === 0" class="custom-tab-underline"></view>\n        </view>\n        <view\n          class="custom-tab"\n          :class="{ active: recordState.current === 1 }"\n          @click="tabChange(1)"\n        >\n          {{ recordState.subsectionList[1].name }}\n          <view v-if="recordState.current === 1" class="custom-tab-underline"></view>\n        </view>\n      </view>\n      <view class="notice-bar-content">\n        <u-notice-bar\n          border-radius="8"\n          mode="horizontal"\n          bg-color="rgba(51,102,255,0.10)"\n          :list="recordState.topList"\n          color="#3366FF"\n          volume-icon="false"\n        ></u-notice-bar>\n      </view>\n      <view class="scroll-content">\n        <u-picker\n          v-model="recordState.dateShow"\n          mode="time"\n          title="请选择工时对应时间"\n          @confirm="onTimeConfirm"\n          @cancel="onCancel"\n        ></u-picker>\n        <u-form-item\n          required="true"\n          label-position="top"\n          label="请选择工时对应时间"\n          prop="dailyDate"\n          :rules="rules"\n        >\n          <u-input\n            border="true"\n            placeholder="请选择工时对应时间"\n            type="select"\n            v-model:modelValue="recordState.dailyDate"\n            @click="recordState.dateShow = true"\n          ></u-input>\n        </u-form-item>\n\n        <view class="project-daily" v-if="recordState.current === 1">\n          <u-form :model="item" ref="projectDailyRef" :borderBottom="false">\n            <view\n              class="project-daily-item"\n              :class="{ \'bottom-border\': recordState.projectDailyData.length > 1 }"\n              v-for="(item, index) in recordState.projectDailyData"\n              :key="index"\n            >\n              <view class="daily-father-project">\n                <view class="daily-title">项目{{ index + 1 }}</view>\n              </view>\n\n              <u-form-item label-position="top" label="项目名称或代号" :borderBottom="false">\n                <u-input\n                  border="true"\n                  v-model:modelValue="item.projectName"\n                  class="input-disabled"\n                ></u-input>\n              </u-form-item>\n              <u-form-item label-position="top" label="工时">\n                <u-input\n                  type="number"\n                  border="true"\n                  class="work-hour-input"\n                  placeholder="请输入工时"\n                  v-model:modelValue="item.workingHours"\n                  @blur="projectInputChange(index)"\n                ></u-input>\n                <view v-if="item.isValid === false" class="valid-span"\n                  >请输入大于0小于等于8的数字(支持0.5的倍数)</view\n                >\n              </u-form-item>\n            </view>\n          </u-form>\n        </view>\n\n        <view class="task-daily" v-else>\n          <u-form :model="item" ref="taskDailyRef" :rules="rules">\n            <view\n              class="task-daily-item"\n              :class="{ \'bottom-border\': recordState.taskDailyData.length > 1 }"\n              v-for="(item, index) in recordState.taskDailyData"\n              :key="index"\n            >\n              <view class="daily-father-task">\n                <view class="daily-title">任务{{ index + 1 }}</view>\n              </view>\n\n              <u-form-item label-position="top" label="项目名称或代号">\n                <u-input\n                  border="true"\n                  v-model:modelValue="item.projectName"\n                  class="input-disabled"\n                ></u-input>\n              </u-form-item>\n              <u-form-item label-position="top" label="里程碑项目阶段/用户故事">\n                <u-input\n                  border="true"\n                  v-model:modelValue="item.milepostName"\n                  class="input-disabled"\n                ></u-input>\n              </u-form-item>\n              <u-form-item label-position="top" label="任务">\n                <u-input\n                  border="true"\n                  v-model:modelValue="item.taskName"\n                  class="input-disabled"\n                ></u-input>\n              </u-form-item>\n              <u-form-item label-position="top" label="工时">\n                <u-input\n                  type="number"\n                  border="true"\n                  placeholder="请输入工时"\n                  v-model:modelValue="item.workingHours"\n                  @blur="taskInputChange(index)"\n                ></u-input>\n                <view v-if="item.isValid === false" class="valid-span"\n                  >请输入大于0小于等于8的数字(支持0.5的倍数)</view\n                >\n              </u-form-item>\n              <u-form-item\n                label-position="top"\n                label="是否有风险"\n                :prop="[index, \'risk\']"\n                style="margin-top: 10px"\n              >\n                <u-radio-group v-model="item.risk" @change="radioGroupChange">\n                  <u-radio\n                    v-for="(item, index) in recordState.riskList"\n                    :key="index"\n                    :name="item.name"\n                    :disabled="item.disabled"\n                  >\n                    {{ item.name }}\n                  </u-radio>\n                </u-radio-group>\n              </u-form-item>\n              <u-form-item\n                label-position="top"\n                label="风险描述"\n                :prop="[index, \'riskDescription\']"\n                v-if="item.risk === \'是\'"\n              >\n                <u-input\n                  border="true"\n                  placeholder="请输入风险描述"\n                  v-model:modelValue="item.riskDescription"\n                ></u-input>\n              </u-form-item>\n              <u-form-item\n                label-position="top"\n                label="解决方案"\n                :prop="[index, \'solution\']"\n                v-if="item.risk === \'是\'"\n              >\n                <u-input\n                  border="true"\n                  placeholder="请输入解决方案"\n                  v-model:modelValue="item.solution"\n                ></u-input>\n              </u-form-item>\n            </view>\n          </u-form>\n          <!-- 行动项任务 -->\n          <u-form :model="item" ref="taskDailyRef" :rules="rules">\n            <view\n              class="task-daily-item"\n              :class="{ \'bottom-border\': recordState.actionDailyData.length > 1 }"\n              v-for="(item, index) in recordState.actionDailyData"\n              :key="index"\n            >\n              <view class="daily-father-project">\n                <view class="daily-title">行动项任务{{ index + 1 }}</view>\n              </view>\n\n              <u-form-item label-position="top" label="项目名称或代号">\n                <u-input\n                  border="true"\n                  v-model:modelValue="item.projectName"\n                  class="input-disabled"\n                ></u-input>\n              </u-form-item>\n              <u-form-item label-position="top" label="行动项任务">\n                <u-input\n                  border="true"\n                  v-model:modelValue="item.taskName"\n                  class="input-disabled"\n                ></u-input>\n              </u-form-item>\n              <u-form-item label-position="top" label="工时">\n                <u-input\n                  type="number"\n                  border="true"\n                  placeholder="请输入工时"\n                  v-model:modelValue="item.workingHours"\n                  @blur="taskInputChange(index)"\n                ></u-input>\n                <view v-if="item.isValid === false" class="valid-span"\n                  >请输入大于0小于等于8的数字(支持0.5的倍数)</view\n                >\n              </u-form-item>\n              <u-form-item\n                label-position="top"\n                label="是否有风险"\n                :prop="[index, \'risk\']"\n                style="margin-top: 10px"\n              >\n                <u-radio-group v-model="item.risk" @change="radioActionGroupChange">\n                  <u-radio\n                    v-for="(item, index) in recordState.riskList"\n                    :key="index"\n                    :name="item.name"\n                    :disabled="item.disabled"\n                  >\n                    {{ item.name }}\n                  </u-radio>\n                </u-radio-group>\n              </u-form-item>\n              <u-form-item\n                label-position="top"\n                label="风险描述"\n                :prop="[index, \'riskDescription\']"\n                v-if="item.risk === \'是\'"\n              >\n                <u-input\n                  border="true"\n                  placeholder="请输入风险描述"\n                  v-model:modelValue="item.riskDescription"\n                ></u-input>\n              </u-form-item>\n              <u-form-item\n                label-position="top"\n                label="解决方案"\n                :prop="[index, \'solution\']"\n                v-if="item.risk === \'是\'"\n              >\n                <u-input\n                  border="true"\n                  placeholder="请输入解决方案"\n                  v-model:modelValue="item.solution"\n                ></u-input>\n              </u-form-item>\n            </view>\n          </u-form>\n        </view>\n        <!-- end -->\n      </view>\n    </view>\n    <view class="bottom-btn">\n      <u-button :custom-style="customStyle" @click="handlerCancel">取消</u-button>\n      <u-button :custom-style="customStyle" @click="handlerSubmit(false)">保存</u-button>\n      <u-button :custom-style="customStyleSubmit" @click="handlerSubmit(true)">保存并提交</u-button>\n    </view>',
  });

  // ============================ 属性定义 ============================

  // ---------------------------- 元素数据引用 ----------------------------
  // 组件 自定义模板_zr0ranbda9 ref 的引用
  const vid_1a58lh4qgl_ref = ref(null);
  // 动态key的map
  const fieldTypeMap = {};
  // 动态key的map
  const refMap = { vid_1a58lh4qgl_ref };

  const showState = reactive({
    vid_1a58lh4qgl_visible: true,
  });
  // ============================ 元素数据引用 ============================

  // ---------------------------- 数据 ----------------------------

  // ============================ 数据 ============================

  // ---------------------------- 方法 ----------------------------
  // ---------------------------- 页面数据 ----------------------------

  // ============================ 页面数据 ============================

  // ---------------------------- 数据字典 ----------------------------

  // ============================ 数据字典 ============================

  // ---------------------------- 响应 ----------------------------

  // 页面交互 跳转
  const response_tdp6tttpbr = async () => {
    // 跳转到目标页面
    /*** UNI_APP_EXEGESIS ***
        handleRedirect(`/pages/Page50001874/Page50001874?`)
         *** UNI_APP_EXEGESIS ***/
  };

  // ============================ 响应 ============================

  // ---------------------------- 函数 ----------------------------

  // 自定义函数 返回上一页
  const customFunction_goBack_txddwnrqtt = (params) => {
    uni.navigateBack();
  };

  // ============================ 函数 ============================

  // ---------------------------- 页面参数 ----------------------------

  const pageParameter_state = reactive({
    processInstanceId: undefined,
  });

  // ============================ 页面参数 ============================

  // ---------------------------- 组件事件处理方法 ----------------------------

  // ============================ 组件事件处理方法 ============================

  // ============================ 方法 ============================

  // ---------------------------- 生命周期 ----------------------------
  /*** UNI_APP_EXEGESIS ***
      // 获取上一层传递的数据
      const workflowChannel = new BroadcastMessage('WORKFLOW');
      workflowChannel.publish({ status: 'Ready' });
      workflowChannel.subscribe((data) => {
        if (data) {
          isProcessState.value = (window.self !== window.parent && data.type === 'hideHeader');
        }
      });
      *** UNI_APP_EXEGESIS ***/

  const pageScrollTop = ref(0);

  // *** PREVIEW_EXEGESIS ***
  onMounted(() => {
    setPageParams(route.query);
    // 设置表单的rule
    try {
    } catch {
      // do nothing
    }
  });
  // *** PREVIEW_EXEGESIS *** //

  /*** UNI_APP_EXEGESIS ***
  const routeOption = ref({})
  onLoad((option) => {
    routeOption.value = option;
  });
  onReady(() => {
    setPageParams(routeOption.value)
    // 设置表单的rule
    try{

    }catch{
        // do nothing
    }
  });
  // 图表刷新标记
  const uChartsReshowFlag = ref(false);
  onHide(() => { // 页面隐藏后标记置为false(如果不置为false无法触发图表更新)
      uChartsReshowFlag.value = false
  })
  onShow(() => {
      uChartsReshowFlag.value = true; // 页面激活后,标记置为true

      setPageParams(routeOption.value)
  })
  onPageScroll(e => {
      pageScrollTop.value = e.scrollTop
  });
  *** UNI_APP_EXEGESIS ***/

  let setPageParams = (routerParam) => {
    const pageParams = [{ dataType: 'STRING', name: 'processInstanceId' }];
    const strategyMap = {
      STRING: (param, paramValue) => {
        pageParameter_state[param.name] = paramValue;
      },
      BOOLEAN: (param, paramValue) => {
        if ('true' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = true;
        } else if ('false' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = false;
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      NUMBER: (param, paramValue) => {
        if (!isNaN(paramValue)) {
          pageParameter_state[param.name] = Number(paramValue);
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      ARRAY: (param, paramValue) => {
        if (isNullOrUnDef(paramValue) || !paramValue || paramValue === 'undefined') {
          // default value
          pageParameter_state[param.name] = [];
        } else if (paramValue.trim().startsWith('[') && paramValue.trim().endsWith(']')) {
          try {
            pageParameter_state[param.name] = JSON.parse(decodeURI(paramValue));
          } catch (error) {
            console.error('参数解析失败 ', error);
          }
        } else {
          console.error('参数传入错误！类型不匹配！');
        }
      },
    };
    pageParams.forEach((param) => {
      strategyMap[param.dataType](param, routerParam[param.name]);
    });
  };

  onUnmounted(() => {
    // 销毁定时器
    setTimeOutList.forEach(({ repeat, timer }) => {
      repeat ? clearInterval(timer) : clearTimeout(timer);
    });
  });

  /*** UNI_APP_EXEGESIS ***
  onPullDownRefresh(() => {
    // 下拉刷新
    setTimeout(() => {
        uni.stopPullDownRefresh()
    }, 1000)
  })
  *** UNI_APP_EXEGESIS ***/

  // ============================ 生命周期 ============================

  // ---------------------------- 数据关联处理 ----------------------------
  // ---------------------------- 组件数据同步 ----------------------------

  // ============================ 组件数据同步 ============================
  //
  // ============================ 数据关联处理 ============================

  // ---------------------- 不同组件自定义的处理逻辑 ---------------------

  // ====================== 不同组件自定义的处理逻辑 ======================

  // ================================定制化逻辑========================================
  onMounted(() => {
    setPageStyle('cyrb-page');
  });

  function setPageStyle(newClass) {
    // #ifdef H5
    // 仅在 H5 执行
    const appDiv = document.querySelector('#app');
    if (appDiv) {
      appDiv.className = '';

      // 再添加当前需要的类
      if (newClass) {
        appDiv.classList.add(newClass);
      }
    }

    const topHeader = document.querySelector('.uni-page-head');
    if (topHeader) topHeader.remove();

    const wrapper = document.querySelector('uni-page-wrapper');
    if (wrapper) wrapper.style.height = '100%';
    // #endif

    // #ifdef MP
    // 小程序端执行（如果你要做兼容逻辑，可以写这里）
    console.log('当前是小程序环境，不需要处理头部或背景');
    // #endif
  }
  const projectDailyRef = ref(null);
  const taskDailyRef = ref(null);
  const rules = {
    dailyDate: [{ type: 'string', required: true, message: '请选择工时对应时间', trigger: 'blur' }],
    projectCode: [{ type: 'string', required: true, message: '请选择项目名称', trigger: 'blur' }],
    milepostName: [{ type: 'string', required: true, message: '请选择项目阶段', trigger: 'blur' }],
    taskName: [{ type: 'string', required: true, message: '请选择任务', trigger: 'blur' }],
    workingHours: [
      {
        required: true,
        validator: validateWorkingHours,
        message: '请输入大于0的数字(支持0.5的倍数)',
        trigger: 'blur',
      },
    ],
    dailyContent: [{ type: 'string', required: true, message: '请输入事项描述', trigger: 'blur' }],
    eventStatus: [{ type: 'string', required: true, message: '请选择事项状态', trigger: 'blur' }],
    estimatedTimeOfCompletion: [
      { type: 'string', required: true, message: '请选择预计完成时间', trigger: 'blur' },
    ],
    riskStatus: [{ type: 'string', required: true, message: '请选择是否有风险', trigger: 'blur' }],
  };
  function validateWorkingHours(rule, value, callback) {
    if (!/^(0(\.5)?|[1-7](\.0|\.5)?|8(\.0)?)$/.test(value)) {
      callback(new Error('请输入有效的工时(支持0.5的数字)'));
    } else {
      callback();
    }
  }
  const customStyle = reactive({
    backgroundColor: '#fff',
    color: ' rgba(0,0,0,0.65)',
    borderRadius: '4px',
    fontWeight: '500',
    borderColor: '#fff',
  });
  const customStyleSubmit = reactive({
    borderRadius: '8rpx',
    backgroundImage: 'linear-gradient(-67deg, #82B0FF 0%, #3366FF 74%)',
    borderColor: '#fff',
    color: '#fff',
  });
  const recordState = reactive({
    subsectionList: [
      {
        name: '任务日报',
      },
      {
        name: '项目日报',
      },
    ],
    current: 0,
    isStage: false,
    tip: ['变更填报日期后将会清空已编辑的日报数据', '需要重新选择和编辑。'],
    dateShow: false,
    projectCodeShow: false,
    // 时间
    dailyDate: undefined,
    // 项目选择列表
    projectCodeList: [],
    // 选中的项目id
    projectCode: undefined,
    // 项目阶段
    milepostShow: false,
    // 项目阶段列表
    milepostList: [],
    // 选中的项目阶段
    milepostName: undefined,
    // 选择项目阶段的id（查询任务需要）
    milepostId: null,
    taskName: undefined,
    // 工时
    workingHours: undefined,
    // 任务id（提交需要用）
    taskId: [],
    // 事项描述
    dailyContent: '',
    // 事项状态
    eventStatus: '正常推进中',
    // 事项状态列表
    eventStatusList: [
      {
        label: '正常推进中',
        value: '正常推进中',
      },
      {
        label: '推进有困难',
        value: '推进有困难',
      },
      {
        label: '已完成',
        value: '已完成',
      },
    ],
    eventStatusShow: false,
    estimatedTimeOfCompletionShow: false,
    riskList: [
      {
        name: '是',
      },
      {
        name: '否',
      },
    ],
    riskStatus: '否',
    riskActionStatus: '否',
    // 风险描述
    riskDescription: '',
    // 解决方案
    solution: '',
    taskDailyData: [],
    projectDailyData: [],
    actionDailyData: [],
    isSaveAndSubmit: false,
    topList: [],
    allHour: 0,
    show: false,
  });
  var currentURL = window.location.href;
  if (currentURL.includes('stage')) {
    recordState.isStage = true;
  } else {
    recordState.isStage = false;
  }

  // 是否有风险
  function radioGroupChange(name) {
    recordState.riskStatus = name;
  }
  function radioActionGroupChange(name) {
    recordState.riskActionStatus = name;
  }

  // 取消按钮
  function handlerCancel() {
    try {
      backHomePage();
      recordForm.value.resetFields();
    } catch (e) {
      console.log(e);
    }
  }

  function validateTasks(tasks, projects, actiontasks) {
    console.log(actiontasks, 'actiontasks');
    const tip = {
      taskrisk: [],
      taskvalid: [],
      projectvalid: [],
      actiontasksrisk: [],
      actiontasksvalid: [],
    };
    actiontasks.forEach((task, index) => {
      // 校验 isValid 是否为 true
      if (!task.isValid) {
        tip.actiontasksvalid.push(index + 1);
      }

      // 校验 risk 是否为 '是'，并检查 solution 和 riskDescription 是否为空
      if (task.risk === '是' && (!task.solution || !task.riskDescription)) {
        tip.actiontasksrisk.push(index + 1);
      }
    });
    tasks.forEach((task, index) => {
      // 校验 isValid 是否为 true
      if (!task.isValid) {
        tip.taskvalid.push(index + 1);
      }

      // 校验 risk 是否为 '是'，并检查 solution 和 riskDescription 是否为空
      if (task.risk === '是' && (!task.solution || !task.riskDescription)) {
        tip.taskrisk.push(index + 1);
      }
    });

    projects.forEach((project, index) => {
      if (!project.isValid) {
        tip.projectvalid.push(index + 1);
      }
    });

    return tip;
  }
  const maskShow = ref(false);
  const maskTip = ref('正在保存请稍后...');
  // 保存日报
  function handlerSubmit(flag) {
    let tasks = recordState.taskDailyData;
    let actiontasks = recordState.actionDailyData;
    let projects = recordState.projectDailyData;
    const tip = validateTasks(tasks, projects, actiontasks);
    const ppmDailyItems = [
      ...recordState.projectDailyData,
      ...recordState.taskDailyData,
      ...recordState.actionDailyData,
    ];
    ppmDailyItems.forEach((item) => {
      item.workingHours = Number(item.workingHours);
    });
    console.log(tip, 'tip');
    const allZeroWorkingHours = ppmDailyItems.every((task) => task.workingHours === 0);
    if (tip.taskvalid.length > 0) {
      uni.showToast({
        title: `任务 ${tip.taskvalid.join('、')} 的工时不合法`,
        icon: 'error',
      });
    } else if (tip.projectvalid.length > 0) {
      uni.showToast({
        title: `项目 ${tip.projectvalid.join('、')} 的工时不合法`,
        icon: 'error',
      });
    } else if (tip.taskrisk.length > 0) {
      uni.showToast({
        title: `任务 ${tip.taskrisk.join('、')} 缺少风险描述或解决方案`,
        icon: 'error',
      });
    } else if (tip.actiontasksvalid.length > 0) {
      uni.showToast({
        title: `行动项任务 ${tip.taskvalid.join('、')} 的工时不合法`,
        icon: 'error',
      });
    } else if (tip.actiontasksrisk.length > 0) {
      uni.showToast({
        title: `行动项任务 ${tip.actiontasksrisk.join('、')} 缺少风险描述或解决方案`,
        icon: 'error',
      });
    } else if (allZeroWorkingHours) {
      uni.showToast({
        title: '总工时不能为0',
        icon: 'error',
      });
    } else {
      recordState.isSaveAndSubmit = flag;
      if (flag === false) {
        handleConfirmSubmit();
      } else {
        recordState.show = true;
      }
    }
  }

  function handleConfirmSubmit() {
    maskShow.value = true;
    if (recordState.isSaveAndSubmit) {
      maskTip.value = '正在提交请稍后...';
    } else {
      maskTip.value = '正在保存请稍后...';
    }
    const ppmDailyItems = [
      ...recordState.projectDailyData,
      ...recordState.taskDailyData,
      ...recordState.actionDailyData,
    ];
    post('/solution-ppm/api/v2/built-in-system-ppm/daily/add/PpmDaily', {
      ppmDailyItems,
      dailyDate: recordState.dailyDate,
      isSubmit: recordState.isSaveAndSubmit === true ? true : false,
    })
      .then((data) => {
        if (data.code === 200) {
          if (recordState.isSaveAndSubmit) {
            uni.showToast({
              title: '提交成功',
              icon: 'success',
            });
            maskShow.value = false;
            recordState.show = false;
            backHomePage();
          } else {
            uni.showToast({
              title: '保存成功',
              icon: 'success',
            });
            recordState.show = false;
            maskShow.value = false;
            backHomePage();
          }
        } else {
          uni.showToast({
            title: `${data.message}`,
            icon: 'error',
          });
          maskShow.value = false;
        }
      })
      .catch((err) => {
        message.error(err.errorFields[0].errors[0]);
        maskShow.value = false;
      });
  }
  const backHomePage = async () => {
    const isLocal = window.location.host.includes('localhost');
    const url = isLocal ? '/pages/home/home' : '/pages/Page3000001233/Page3000001233';
    handleRedirect(url);
  };

  // 新-项目日报
  function tabChange(index) {
    recordState.current = index;
  }
  const formattedDate = dayjs().format('YYYY-MM-DD');
  recordState.dailyDate = formattedDate;
  function getDailyData() {
    post('/solution-ppm/api/v2/built-in-system-ppm/daily_report/for_create', {
      dailyDate: recordState.dailyDate,
    }).then((data) => {
      if (data.code === 200) {
        recordState.projectDailyData = data.data.projectList.map((item) => {
          return {
            ...item,
            isValid: true,
          };
        });
        recordState.taskDailyData = data.data.taskList.map((item) => {
          return {
            ...item,
            isValid: true,
          };
        });
        recordState.actionDailyData = data.data.actionTaskList?.map((item) => {
          return {
            ...item,
            isValid: true,
          };
        });
        recordState.allHour = data.data.workHours;
        recordState.visible = true;
      }
    });
  }
  getDailyData();
  function onTimeConfirm(params) {
    recordState.dailyDate = `${params.year}-${params.month}-${params.day}`;
    getDailyData();
  }

  // 测试
  function projectInputChange(index) {
    let value = recordState.projectDailyData[index].workingHours;
    if (!/^(0(\.5)?|[1-9](\d*)?(\.5)?(\.0)?)$/.test(value)) {
      recordState.projectDailyData[index].isValid = false;
    } else {
      recordState.projectDailyData[index].isValid = true;
    }
  }
  function taskInputChange(index) {
    let value = recordState.taskDailyData[index].workingHours;
    if (!/^(0(\.5)?|[1-9](\d*)?(\.5)?(\.0)?)$/.test(value)) {
      recordState.taskDailyData[index].isValid = false;
    } else {
      recordState.taskDailyData[index].isValid = true;
    }
  }
  watch(
    () => [recordState.projectDailyData, recordState.taskDailyData, ...recordState.actionDailyData],
    () => {
      let allData = [
        ...recordState.projectDailyData,
        ...recordState.taskDailyData,
        ...recordState.actionDailyData,
      ];
      let totalWorkingHours = allData.reduce(
        (sum, item) => Number(sum) + Number(item.workingHours),
        0,
      );
      console.log('Total working hours:', totalWorkingHours);
      recordState.editHour = totalWorkingHours;
      recordState.topList = [
        `正在编辑工时：${totalWorkingHours}工时,今日已提交总工时（不含本次提交）${recordState.allHour}工时`,
      ];
    },
    { deep: true },
  );
</script>
<style lang="less" scoped>
  .page_root {
    min-height: 100%;
    box-sizing: border-box;
    overflow: auto;
  }

  .page_root {
    min-height: 100%;
    box-sizing: border-box;
    background-image: url('http://10.40.0.33:9001/file-storage/540437262415247360-source.png');
    background-size: cover;
    padding: 40rpx;
    opacity: 1;
  }

  /*
    新建日报
    */
  .daily-title {
    font-size: 28rpx;
    color: #262626;
    letter-spacing: 0;
    font-weight: 600;
    font-size: 32rpx;
    color: rgba(0, 0, 0, 0.85);
    line-height: 44rpx;
    font-weight: 600;
  }

  .daily-father-project {
    position: relative;
    height: 17px;
    margin-bottom: 32rpx;
  }

  .daily-father-task {
    position: relative;
    height: 17px;
    margin-bottom: 32rpx;
  }

  .input-disabled {
    pointer-events: none;
    /* 阻止元素接收鼠标事件 */
  }

  .task-daily-item {
    margin-top: 16px;
  }

  .project-daily-item {
    margin-top: 16px;
  }

  .bottom-border {
    border-bottom: 1px solid #d9d9d9;
  }

  :deep(.u-form-item) {
    padding: 0;
  }

  .custom-tabs {
    display: flex;
    position: relative;
    height: 140rpx;
    border-radius: 16rpx;
  }

  .custom-tab {
    flex: 1;
    text-align: center;
    cursor: pointer;
    padding: 38rpx;
    background-color: transparent;
    position: relative;
    font-size: 32rpx;
    color: rgba(0, 0, 0, 0.65);
    line-height: 44px;
    font-weight: 400;
  }
  .custom-tab.active {
    background-color: transparent;
    font-size: 32rpx;
    color: #000000;
    line-height: 44rpx;
    font-weight: 500;
  }

  .work-hour-input {
    position: relative;
  }

  .valid-span {
    position: absolute;
    bottom: -35%;
    font-size: 0.75rem;
    color: #fa3534;
  }

  .warp {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .rect {
    width: 120px;
    height: 120px;
    color: #fff;
  }
  :deep(.u-navbar) {
    background-color: transparent !important;
    padding: 0 40rpx 0 0;
    border: none;
  }
  .custom-tab-underline {
    width: 100rpx;
    height: 4rpx;
    background-color: #fff;
  }
  .custom-tab-underline {
    position: absolute;
    left: 50%;
    top: 70%;
    transform: translateX(-50%);
    border-radius: 8rpx;
    height: 8rpx;
    background-image: linear-gradient(87deg, #7353f7 0%, #3366ff 100%);
  }
  .card {
    background-image: url('http://10.40.0.33:9001/file-storage/540446451155941376-source.png');
    background-size: cover;
    border-radius: 24rpx;
    height: calc(100vh - 340rpx);
    overflow: hidden;
  }
  .bottom-btn {
    display: flex;
    justify-content: space-between;
    margin-top: 32rpx;
    padding: 0;
    gap: 29rpx;
  }
  .bottom-btn :deep(.u-btn) {
    margin: 0 !important;
    border: none !important;
    flex: 1;
  }
  :deep(.u-form-item--left__content__label) {
    color: rgba(0, 0, 0, 0.45);
    font-weight: 400;
  }
  :deep(.u-input) {
    background-color: #fff;
  }
  .top-count {
    font-size: 24rpx;
    color: #3366ff;
    line-height: 32rpx;
    font-weight: 400;
    border-radius: 8rpx;
    background: rgba(51, 102, 255, 0.1);
    padding: 16rpx 32rpx;
  }
  .scroll-content {
    border-radius: 4px;
    height: calc(100vh - 310px);
    overflow: auto;
    padding: 30rpx;
  }
  .notice-bar-content {
    padding: 0 30rpx;
  }
</style>
